package com.example.demo.controller;

import com.example.demo.config.recode.ReCode;
import com.example.demo.config.recode.ReCodeManage;
import com.example.demo.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
@Slf4j
@RequiredArgsConstructor
@Controller
@RequestMapping("/login/{appid}")
public class LoginController {

    private final WxMpService wxService;
    @Autowired
    private ReCodeManage reCodeManage;
    /**
     * 发码
     * @return
     */
    @ResponseBody
    @GetMapping("sendcode")
    public R sendcode(@PathVariable String appid,HttpServletRequest request){
        String code = UUID.randomUUID().toString();
        reCodeManage.saveCode( code );
        String redirect_uri=request.getScheme()+"://"+request.getServerName()+"/login/"+appid+"/logincode?code="+code;
        String find_uri=request.getScheme()+"://"+request.getServerName()+"/login/"+appid+"/findcode?code="+code;
        String okcode=request.getScheme()+"://"+request.getServerName()+"/login/"+appid+"/okcode?code="+code;
        return R.ok().put( reCodeManage.getCode(code) ).put( "redirect_uri", redirect_uri).put( "find",find_uri ).put( "okcode",okcode );
    }

    /**
     * 查看二维码状态
     * @return
     */
    @ResponseBody
    @GetMapping("findcode")
    public R findcode(@PathVariable String appid,String code){
        ReCode code1 = reCodeManage.getCode( code );
        return R.ok().put( code1 );
    }

    /**
     * 微信跳转地址
     * @return
     */
    @GetMapping("logincode")
    public String logincode(@PathVariable String appid,String code, HttpServletRequest request){
        reCodeManage.isread(code);
        String redirect_uri=request.getScheme()+"://"+request.getServerName()+"/login/"+appid+"/getcode";
        return wxlogin(appid,"snsapi_userinfo",redirect_uri)+"&state="+code;
    }
    private String wxlogin(@PathVariable String appid, @PathVariable String scope, String redirect_uri) {
        return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid +
                "&redirect_uri="+redirect_uri+"&response_type=code&" +
                "scope="+scope+"";
    }
    @CrossOrigin
    @ResponseBody
    @GetMapping("getcode")
    public R getcode(@PathVariable String appid,
                     @RequestParam(required = false) String code,String state){
        if(!StringUtils.isEmpty(code)){
            WxMpOAuth2AccessToken authUrl= null;
            try {

                wxService.switchoverTo( appid );
                authUrl = wxService.oauth2getAccessToken(code);
                reCodeManage.setCode( state, authUrl);
                WxMpUser mpUser = wxService.oauth2getUserInfo( authUrl, "zh_CN" );
                reCodeManage.setUser( state, mpUser);
                log.info("微信信息："+authUrl);
                return R.ok().msg( "获取成功" ).put( mpUser );
            } catch (WxErrorException e) {
                e.printStackTrace();
                return R.error(e).msg( "获取失败" );
            }

        }else{
            return R.error( "code参数不存在" );
        }

    }
}
